package com.jingdianjichi.subject.domain.config;

import org.apache.commons.lang3.StringUtils;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 可以自定义名称的线程工厂,我们不用默认的了,你可以去做扩展的亲
 */
public class CustomNameThreadFactory implements ThreadFactory {

    private static final AtomicInteger poolNumber = new AtomicInteger(1);
    private final ThreadGroup group;
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;

    //自定义一下,否则我们的工厂在看日志的时候是非常麻烦的亲
    CustomNameThreadFactory(String name) {
        @SuppressWarnings("removal")
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() :
                Thread.currentThread().getThreadGroup();

        if (StringUtils.isBlank(name)){
            name="pool";
        }

        //自定义名称亲
        namePrefix =name+"-"+
                poolNumber.getAndIncrement() +
                "-thread-";
    }


    //我们重写一下工厂就是加一个名字
    @Override
    public Thread newThread(Runnable r) {
        Thread thread = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);

        //判断是不是守护线程
        if (thread.isDaemon()) {
            thread.setDaemon(false);
        }

        //判断优先级来的
        if (thread.getPriority() != Thread.NORM_PRIORITY){
            thread.setPriority(Thread.NORM_PRIORITY);
        }

        return thread;
    }


}
